package com.yunlinker.asba;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Vibrator;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;
import android.text.TextUtils;
import android.util.Log;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.yunlinker.asba.activity.MainActivity;
import com.yunlinker.asba.bean.CrashHandler;
import com.yunlinker.asba.helper.MyActivityManager;
import com.yunlinker.asba.helper.MySharePreferenceHelper;
import com.yunlinker.asba.utils.DemoCache;
import com.yunlinker.asba.utils.FrescoImageLoader;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.qiyukf.nimlib.sdk.NimIntent;
import com.qiyukf.unicorn.api.OnBotEventListener;
import com.qiyukf.unicorn.api.SavePowerConfig;
import com.qiyukf.unicorn.api.StatusBarNotificationConfig;
import com.qiyukf.unicorn.api.UICustomization;
import com.qiyukf.unicorn.api.Unicorn;
import com.qiyukf.unicorn.api.YSFOptions;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.cookie.CookieJarImpl;
import com.zhy.http.okhttp.cookie.store.PersistentCookieStore;
import com.zhy.http.okhttp.https.HttpsUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import okhttp3.OkHttpClient;


public class MainApplication extends MultiDexApplication {


    public static String APPID ="";
    private static MainApplication sInstance;
    private Handler mHandler = new Handler();
    private MyActivityManager activityManager = null;
    public static Context applicationContext;

    public boolean isRefreshHome = false;
    public String isRefreshUrl = "";
    public String currentFileName = "";

    public Vibrator mVibrator;

    public static  String userTimeSpan = "";

    public static String ALiUpLoadToken = "";
    public static int activiedActicity = 0;

    public static int mUploadType;
    public static int mUploadSize;

    {
        PlatformConfig.setWeixin("wxd2c013473d936366", "475a149ddf530eebc35168b88c51223a");
        PlatformConfig.setQQZone("1106187214"/*"1106430965"*/, "DEx4kvbhRiYqixpC"/*"ARutXZe81PN1An1W"*/);
        PlatformConfig.setSinaWeibo("3921700954", "04b48b094faeb16683c32669824ebdad", "http://sns.whalecloud.com");
//        Config.DEBUG = true;
    }


    private StatusBarNotificationConfig mStatusBarNotificationConfig;
    //----qiyu---如果返回值为null，则全部使用默认参数。
    private YSFOptions options() {
        YSFOptions options = new YSFOptions();
        options.statusBarNotificationConfig = new StatusBarNotificationConfig();
        options.statusBarNotificationConfig.notificationSmallIconId = R.mipmap.app;
        options.savePowerConfig = new SavePowerConfig();
        options.uiCustomization = new UICustomization();
        options.uiCustomization.leftAvatar = "mipmap://"+R.mipmap.app;
        options.uiCustomization.msgItemBackgroundLeft = R.drawable.ysf_message_left_bg_selector;
        options.uiCustomization.msgItemBackgroundRight = R.drawable.ysf_message_right_bg_selector;
        options.onBotEventListener = new OnBotEventListener() {
            @Override
            public boolean onUrlClick(Context context, String url) {
//                Log.d("url",""+url);
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                intent.putExtra(NimIntent.EXTRA_NOTIFY_CONTENT,"客服");
                context.startActivity(intent);
                return true;
            }
        };

        DemoCache.ysfOptions = options;
        return options;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        applicationContext = this;
        sInstance = this;
        CrashHandler handler = new CrashHandler(this);
        Thread.setDefaultUncaughtExceptionHandler(handler);
        MySharePreferenceHelper.setString("__firstLaunch", "1");
        PushAgent mPushAgent = PushAgent.getInstance(this);
        mPushAgent.setMuteDurationSeconds(0);
        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
            @Override
            public void dealWithCustomAction(Context context, UMessage msg) {
                if(MainApplication.activiedActicity == 0) {
                    JSONObject pjb = new JSONObject();
                    if(msg.extra!=null && msg.extra.get("url")!=null) {
                        try {
                            pjb.put("data",msg.extra.get("url"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                    MySharePreferenceHelper.setString("__firstLaunch", "1");
                    MySharePreferenceHelper.setString("pushEvent", pjb.toString());
                    Intent intent=new Intent(context,MainActivity.class);
                    intent.putExtra("um","1");
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                }
            }
        };
        mPushAgent.setNotificationClickHandler(notificationClickHandler);
        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {
            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回device token
				MySharePreferenceHelper.setString("deviceToken", deviceToken);
                System.out.println("---------application start："+deviceToken);
            }

            @Override
            public void onFailure(String s, String s1) {
                System.out.println("---------application start："+s+","+s1);
            }
        });
        if(MySharePreferenceHelper.PREFERENCES.getString("closePush","") == "1"){
            mPushAgent.disable(null);
        }
        mPushAgent.setDebugMode(true);



        setHttpsEnable();

        activityManager = MyActivityManager.getScreenManager();
        activityManager.clearTag();


        UMShareAPI.get(this);


        //----qiyu---
/*        Unicorn.init(this, "89b04e68bf200e447eaf6ac87a1ca1b2", options(), new UILImageLoader(){
            @Nullable
            @Override
            public Bitmap loadImageSync(String uri, int width, int height) {
                return null;
            }
            @Override
            public void loadImage(String uri, int width, int height, ImageLoaderListener listener) {
            }
        });

        if (inMainProcess(this)) {
            ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(this));
        }else {

        }*/
        if (!Unicorn.init(this, "89b04e68bf200e447eaf6ac87a1ca1b2", options(), new FrescoImageLoader(this))) {
            Log.w("demo", "init qiyu sdk error!");
        }

        if (inMainProcess(this)) {
            DemoCache.context = getApplicationContext();
            int memoryCacheSize = (int) (Runtime.getRuntime().maxMemory() / 8);
            ImageLoader.getInstance().init(new ImageLoaderConfiguration.Builder(this)
                    .memoryCacheSize(memoryCacheSize)
                    .diskCacheSize(50 * 1024 * 1024)
                    .build());
            Fresco.initialize(this);
        }
    }


    @TargetApi(Build.VERSION_CODES.DONUT)
    public static boolean inMainProcess(Context context) {
        String mainProcessName = context.getApplicationInfo().processName;
        String processName = getProcessName();
        return TextUtils.equals(mainProcessName, processName);
    }

    private static String getProcessName() {
        BufferedReader reader = null;
        try {
            File file = new File("/proc/" + android.os.Process.myPid() + "/" + "cmdline");
            reader = new BufferedReader(new FileReader(file));
            return reader.readLine().trim();
        } catch (IOException e) {
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * 初始化网络框架
     */
    private void setHttpsEnable() {


        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);

        //设置可访问所有的https网站                                     //设置具体的证书证书的inputstream
        //对于cookie一样，直接通过cookiejar方法配置，参考上面的配置过程。
        CookieJarImpl cookieJar = new CookieJarImpl(new PersistentCookieStore(getApplicationContext()));
        //初始化网络客户端
        OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(10000L, TimeUnit.MILLISECONDS)
                .readTimeout(10000L, TimeUnit.MILLISECONDS).sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager).
                        cookieJar(cookieJar).hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                }).build();
        //其他配置
        OkHttpUtils.initClient(okHttpClient);
    }


    public MyActivityManager getActivityManager() {
        return activityManager;
    }

    public static MainApplication getInstance() {
        return sInstance;
    }

    public Handler getHandler() {
        return mHandler;
    }


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

}
